import axios, { AxiosRequestConfig } from 'axios';
import { getTokenFromCookie } from '@/utils/cookie-util';
import { message } from 'ant-design-vue';
import { clearAllCoolies } from '@/utils/cookie-util';
import { localClear } from '@/utils/local-util';

const TOKEN_HEADER: string = 'token';

const smartAxios = axios.create({
  baseURL: '/api',
  timeout: 15000,
});

// ================================= 请求拦截器 =================================

smartAxios.interceptors.request.use(
  (config) => {
    const token = getTokenFromCookie();
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    if (token) {
      config.headers[TOKEN_HEADER] = token;
    } else {
      delete config.headers[TOKEN_HEADER];
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// ================================= 响应拦截器 =================================
smartAxios.interceptors.response.use(
  (response) => {
    const res = response.data;
    if(res){
      if (res.code && res.code !== 200) {
        if (res.code == 401) {
          message.error('登录失效，请重新登录');
          clearAllCoolies();
          localClear();
          //跳转到登录页面，直接使用页面刷新的策略
          setTimeout(() => {
            location.href = '/web/#/login';
          }, 300);
          return Promise.reject({message:res.msg});
        }
        return Promise.reject({message:res.msg});
      } else {
        return Promise.resolve(res);
      }
    }else{
      return Promise.reject({status:500,message:'网络异常，请稍后重试'});
    }
  },
  (error) => {
    if (error.message.indexOf('timeout') != -1) {
      message.error('网络超时');
    } else if (error.message == 'Network Error') {
      message.error('网络连接错误');
    }else if (error.message.indexOf('Request') != -1) {
      message.error('网络发生错误');
    }
    return Promise.reject(error);
  }
);

// ================================= 对外提供请求方法：通用请求，get， post, 下载download等 =================================

/**
 * 通用请求封装
 * @param config
 */
export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  return smartAxios.request(config);
};

/**
 * post请求
 */
export const postRequest = <T = any>(url: string, data?: any): Promise<T> => {
  return request({ data, url, method: 'post' });
};

/**
 * get请求
 */
export const getRequest = <T = any>(url: string, params?: any): Promise<T> => {
  return request({ url, method: 'get', params });
};

/**
 * 下载
 */
export const download = function (fileName: string, url: string, params?: any): void {
  request({
    method: 'get',
    url: url,
    params: params,
    responseType: 'blob',
  })
    .then((data) => {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
    })
    .catch((error) => {
      console.log(error)
    });
};
